package main

import (
	"encoding/json"
	"encoding/xml"
	"fmt"
)

// 数据格式: json, xml
func main() {
	p := &Person{
		Name: "张三",
		Age:  18,
	}

	// 编码json
	b, _ := json.Marshal(p)
	fmt.Println(string(b))

	// 格式化
	c, _ := json.MarshalIndent(p, "", "  ")
	fmt.Println(string(c))

	// map转json
	strMap := make(map[string]any)
	strMap["name"] = "李四"
	strMap["age"] = 18
	b, _ = json.Marshal(strMap)
	fmt.Println(string(b))

	// 解码
	p0 := &Person{}
	_ = json.Unmarshal(b, p0)
	fmt.Printf("%#v\n", p0)

	// 自动转到map
	var m any
	json.Unmarshal(b, &m)
	fmt.Printf("%#v\n", m)

	// xml
	x, _ := xml.Marshal(p)
	fmt.Println(string(x))

	p1 := &Person{}
	_ = xml.Unmarshal(x, p1)
	fmt.Printf("%#v\n", p1)
}

type Person struct {
	Name    string `json:"name"`
	Age     int    `json:"age"`
	Address string `json:"-"` // json时忽略此字段
}
